<?php
/**
 * @project kkzc
 * @date 2015-7-10
 * @author xialei <xialeistudio@gmail.com>
 */

namespace app\services;


use app\components\Service;
use app\exception\ErrorCode;
use app\models\Order;
use app\models\Train;
use app\models\User;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

/**
 * 推广
 * @author xialei <xialeistudio@gmail.com>
 * Class PromoteService
 * @package app\services
 */
class PromoteService extends Service
{
    /**
     * @author xialei <xialeistudio@gmail.com>
     * @param string $className
     * @return self
     */
    public static function instance($className = __CLASS__)
    {
        if (empty(self::$_instance[$className])) {
            self::$_instance[$className] = new $className();
        }
        return self::$_instance[$className];
    }

    /**
     * 获取用户下线数量
     * @author xialei <xialeistudio@gmail.com>
     * @param $userId
     * @return array
     */
    public function getReferralsCount($userId)
    {
        //一级下线用户ID
        $primaries = User::find()->where(['parent_id' => $userId])->select(['user_id'])->column();
        //二级下线
        $secondary = User::find()->where(['parent_id' => $primaries])->select(['user_id'])->column();
        //三级下线
        $third = User::find()->where(['parent_id' => $secondary])->select(['user_id'])->column();

        return [
            'primary' => count($primaries),
            'secondary' => count($secondary),
            'third' => count($third)
        ];
    }

    /**
     * 获取用户下线中的租客数量
     * @author xialei <xialeistudio@gmail.com>
     * @param $userId
     * @return array
     */
    public function getTenants($userId)
    { //一级下线用户ID
        $primaries = User::find()->where(['parent_id' => $userId, 'role' => User::ROLE_TENANTS])->select(['user_id'])->column();
        //二级下线
        $secondary = User::find()->where(['parent_id' => $primaries, 'role' => User::ROLE_TENANTS])->select(['user_id'])->column();
        //三级下线
        $third = User::find()->where(['parent_id' => $secondary, 'role' => User::ROLE_TENANTS])->select(['user_id'])->column();

        return [
            'primary' => count($primaries),
            'secondary' => count($secondary),
            'third' => count($third)
        ];
    }

    /**
     * 获取车主数量
     * @author xialei <xialeistudio@gmail.com>
     * @param $userId
     * @return array
     */
    public function getOwners($userId)
    {
        $primaries = User::find()->where(['parent_id' => $userId, 'role' => [User::ROLE_OWNER, User::ROLE_BOTH]])->select(['user_id'])->column();
        //二级下线
        $secondary = User::find()->where(['parent_id' => $primaries, 'role' => [User::ROLE_OWNER, User::ROLE_BOTH]])->select(['user_id'])->column();
        //三级下线
        $third = User::find()->where(['parent_id' => $secondary, 'role' => [User::ROLE_OWNER, User::ROLE_BOTH]])->select(['user_id'])->column();

        return [
            'primary' => count($primaries),
            'secondary' => count($secondary),
            'third' => count($third)
        ];
    }


    /**
     * 最近几天内订单数量
     * @author xialei <xialeistudio@gmail.com>
     * @param $userId
     * @param int $day
     * @return array
     * @throws Exception
     */
    public function getOrderCount($userId, $day = 7)
    {
        //获取今天日期
        $today = strtotime(date('Y-m-d'));
        if ($day < 0) {
            throw new Exception('时间间隔不能小于0', ErrorCode::PARAM_ERROR);
        }
        $from = strtotime('-' . $day . 'days', $today);

        $primaries = User::find()->where(['parent_id' => $userId, 'role' => User::ROLE_TENANTS])->select(['user_id'])->column();
        //二级下线
        $secondary = User::find()->where(['parent_id' => $primaries, 'role' => User::ROLE_TENANTS])->select(['user_id'])->column();
        //三级下线
        $third = User::find()->where(['parent_id' => $secondary, 'role' => User::ROLE_TENANTS])->select(['user_id'])->column();

        //订单
        $primariesOrders = Order::find()->where(['user_id' => $primaries, 'state' => Order::STATE_SETTLEMENT])->andWhere([
            'between', 'created_at', $from, $today
        ])->count();
        $secondOrders = Order::find()->where(['user_id' => $secondary, 'state' => Order::STATE_SETTLEMENT])->andWhere([
            'between', 'created_at', $from, $today
        ])->count();
        $thirdOrders = Order::find()->where(['user_id' => $third, 'state' => Order::STATE_SETTLEMENT])->andWhere([
            'between', 'created_at', $from, $today
        ])->count();
        return [
            'primary' => $primariesOrders,
            'secondary' => $secondOrders,
            'third' => $thirdOrders
        ];
    }

    /**
     * 获取注册X天内的车次数据
     * @author xialei <xialeistudio@gmail.com>
     * @param $userId
     * @param int $day
     * @return array
     * @throws Exception
     */
    public function getTrains($userId, $day = 7)
    {
        $primaries = User::find()->where(['parent_id' => $userId, 'role' => User::ROLE_TENANTS])->select(['user_id', 'created_at'])->asArray()->all();
        $primary = 0;
        foreach ($primaries as $row) {
            $from = User::find()->where(['user_id' => $row['user_id']])->select(['created_at'])->scalar();
            $to = strtotime('+' . $day . 'days', $from);
            //统计车次
            $trains = Train::find()->where(['user_id' => $row['user_id']])->andWhere([
                'between', 'count_at', $from, $to
            ])->sum('trains');
            $primary += floatval($trains);
        }

        $userIds = ArrayHelper::getColumn($primaries, 'user_id');
        $secondaries = User::find()->where(['parent_id' => $userIds, 'role' => User::ROLE_TENANTS])->select(['user_id', 'created_at'])->asArray()->all();
        $secondary = 0;
        foreach ($secondaries as $row) {
            $from = User::find()->where(['user_id' => $row['user_id']])->select(['created_at'])->scalar();
            $to = strtotime('+' . $day . 'days', $from);
            //统计车次
            $trains = Train::find()->where(['user_id' => $row['user_id']])->andWhere([
                'between', 'count_at', $from, $to
            ])->sum('trains');
            $secondary += floatval($trains);
        }


        $userIds = ArrayHelper::getColumn($secondaries, 'user_id');
        $thirds = User::find()->where(['parent_id' => $userIds, 'role' => User::ROLE_TENANTS])->select(['user_id', 'created_at'])->asArray()->all();
        $third = 0;
        foreach ($thirds as $row) {
            $from = User::find()->where(['user_id' => $row['user_id']])->select(['created_at'])->scalar();
            $to = strtotime('+' . $day . 'days', $from);
            //统计车次
            $trains = Train::find()->where(['user_id' => $row['user_id']])->andWhere([
                'between', 'count_at', $from, $to
            ])->sum('trains');
            $third += floatval($trains);
        }

        return [
            'primary' => $primary,
            'secondary' => $secondary,
            'third' => $third
        ];
    }

    /**
     * 销售排行
     * @author xialei <xialeistudio@gmail.com>
     * @return array|\yii\db\ActiveRecord[]
     */
    public function rank()
    {
        $data = Train::find()->select(['SUM(trains) as total', 'user_id'])->groupBy(['user_id'])->orderBy(['total' => SORT_DESC])->with(['user'])->asArray()->all();
        return $data;
    }
}